package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.RedisService;
import com.lt.test.api.ShopService;
import com.lt.test.common.exception.CustomException;
import com.lt.test.entity.DO.ShopDO;
import com.lt.test.entity.DTO.CustomUser;
import com.lt.test.entity.DTO.PageDTO;
import com.lt.test.entity.DTO.SuperMarketUserDTO;
import com.lt.test.entity.QueryModel.MapQueryModel;
import com.lt.test.provider.mapper.SPLOrderMapper;
import com.lt.test.provider.mapper.ShopEmpMapper;
import com.lt.test.provider.mapper.ShopMapper;
import com.lt.test.provider.mapper.UserMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service(version = "1.0.0")
public class ShopServiceImpl implements ShopService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private ShopEmpMapper shopEmpMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private SPLOrderMapper splOrderMapper;

    @Override
    public PageDTO<ShopDO> findShopByPage(Integer page, Integer pageSize, String sortedKey, String sortedValue, String filters, Map<String, String> params) throws CustomException {
        Long beginNum = (long) ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

       // PageQueryModel pageQueryModel = new PageQueryModel();
        params.put("beginNum", beginNum.toString());
        params.put("endNum", endNum.toString());

        if ("id".equals(sortedKey)) {
            //pageQueryModel.setSortName("DS.SHOP_ID");
            params.put("sortName", "DS.SHOP_ID");
        } else {
            //pageQueryModel.setSortName("DS.STATE_DATE");
            params.put("sortName", "STATE_DATE");
        }
        //pageQueryModel.setSortOrder();//防止sql注入
        params.put("sortOrder", ("asc".equals(sortedValue) ? "asc" : "desc"));

        //List<PageFilter> filterList = new ArrayList<>();

        if (filters != null && !filters.trim().equals("")) {
            JSONObject jsonObject = JSONObject.fromObject(filters);
            JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject result = (JSONObject) jsonArray.get(i);
                if (com.lt.test.common.util.StringUtils.isNullOrTrimEmpty(params.get(result.get("field").toString())))
                params.put(result.get("field").toString(),result.getString("data"));
            }
        }

        List<ShopDO> shopDOList = null;
        int recordCount = 0;
        try {
            shopDOList = shopMapper.findShopByPage(params);
            recordCount = shopMapper.getShopCount(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取店铺数据失败");
        }
        PageDTO<ShopDO> result = new PageDTO<>(page, pageSize, shopDOList, recordCount);
        return result;
    }

    @Override
    public List<Map<String, Object>> findShopToExportExcel(MapQueryModel params) throws Exception {
        return shopMapper.findShopToExportExcel(params.getStringMap());
    }

    @Override
    public void editShopInfo(ShopDO shop, String oper) throws CustomException {
        switch (oper) {
            case "edit":
                if (shop.getId() == null) {
                    throw new CustomException("更新店铺信息没有主键");
                }
                try {
                    shopMapper.editShopInfo(shop);
//                    if (true) {
//                        ShopEmpDO record = new ShopEmpDO();
//                        record.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
//                        record.setShopId(Integer.valueOf(shop.getId().toString()));
//                        record.setUserId(Integer.valueOf(shop.getUserId().toString()));
//                        record.setOperatorTime(new Date());
//                        record.setEmpType("003");
//                        record.setState("1");
//                        record.setRemark("运维平台修改是否试点: 姓名: " + shop.getCreateTime());
//                        shopEmpMapper.insert(record);
//                        //开辟线程通知用户
//                        //new Thread(new SendShopStatusThread(String.valueOf(shop.getUserId()), String.valueOf(shop.getId()), shop.getStateStr())).start();
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new CustomException("更新店铺信息失败");
                }
                String cache = "cache|shopInfo|" + shop.getId();
                boolean surrcee = redisService.del(cache);
                if (!surrcee) {
                    logger.error("删除店铺缓存失败：" + shop);
                }
                break;

            default:
                throw new CustomException("不知道操作类型");
        }
    }


    @Override
    public List<Map<String, Object>> findShipmentOrderByLsatCreateTime(Map<String, String> params) throws CustomException {
        List<Map<String, Object>> result;

        //初次获取
        if (params.get("lastOrderTime") == null || "".equals(params.get("lastOrderTime"))) {
            try {
                result = shopMapper.findTenShipmentOrder(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取初始化十条出库订单失败");
            }
        } else {
            try {
                result = shopMapper.findShipmentOrderByLastOrderTime(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("根据最后更新时间获取出库订单失败");
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> findShipmentOrderDayData(Map<String, String> params) throws CustomException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.DATE, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2016-11-19";
        try {
            params.put("firstDayStr", firstDayStr);
            List<Map<String, Object>> SPLOrderDayList = shopMapper.findShipmentOrderDayData(params);
            Map<String, Object> result = new HashMap(3, 1.0F);
            List days = new ArrayList(10);
            List prices = new ArrayList(10);
            List sums = new ArrayList(10);
            for (Map<String, Object> SPLOrderDay : SPLOrderDayList) {
                days.add(SPLOrderDay.get("dayNum"));

                Double price = Double.valueOf(SPLOrderDay.get("priceSum").toString());
                Double price1 = price / 10000;
                BigDecimal b = new BigDecimal(price1);
                Double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                for (int i = 3; i < 10; i++) {
                    if (f1 > 0.00) {
                        break;
                    }
                    f1 = b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                prices.add(f1);

                sums.add(SPLOrderDay.get("countNum"));
            }
            result.put("dayNums", days);
            result.put("priceSums", prices);
            result.put("countNums", sums);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按天查询入库订单统计失败");
        }
    }

    @Override
    public Map<String, Object> findShipmentOrderMonthData(Map<String, String> params) throws CustomException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.MONTH, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2015-12";
        try {
            params.put("firstDayStr", firstDayStr);
            List<Map<String, Object>> SPLOrderDayList = shopMapper.findShipmentOrderMonthData(params);
            Map<String, Object> result = new HashMap<>(3, 1.0F);
            List days = new ArrayList(10);
            List prices = new ArrayList(10);
            List sums = new ArrayList(10);
            for (Map<String, Object> SPLOrderDay : SPLOrderDayList) {
                days.add(SPLOrderDay.get("dayNum"));

                Double price = Double.valueOf(SPLOrderDay.get("priceSum").toString());
                Double price1 = price / 10000;
                BigDecimal b = new BigDecimal(price1);
                Double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                for (int i = 3; i < 10; i++) {
                    if (f1 > 0.00) {
                        break;
                    }
                    f1 = b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                prices.add(f1);

                sums.add(SPLOrderDay.get("countNum"));
            }
            result.put("dayNums", days);
            result.put("priceSums", prices);
            result.put("countNums", sums);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按月查询入库订单统计失败");
        }
    }

    @Override
    public Map<String, Object> findShipmentOrderYearData(Map<String, String> params) throws CustomException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.WEEK_OF_YEAR, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-ww");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2015";
        try {
            params.put("firstDayStr", firstDayStr);
            List<Map<String, Object>> SPLOrderDayList = shopMapper.findShipmentOrderYearData(params);
            Map<String, Object> result = new HashMap<>(3, 1.0F);
            List days = new ArrayList(10);
            List prices = new ArrayList(10);
            List sums = new ArrayList(10);
            for (Map<String, Object> SPLOrderDay : SPLOrderDayList) {
                days.add(SPLOrderDay.get("dayNum"));

                Double price = Double.valueOf(SPLOrderDay.get("priceSum").toString());
                Double price1 = price / 10000;
                BigDecimal b = new BigDecimal(price1);
                Double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                for (int i = 3; i < 10; i++) {
                    if (f1 > 0.00) {
                        break;
                    }
                    f1 = b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                prices.add(f1);

                sums.add(SPLOrderDay.get("countNum"));
            }
            result.put("dayNums", days);
            result.put("priceSums", prices);
            result.put("countNums", sums);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按周查询入库订单统计失败");
        }
    }

    @Override
    public List<Map<String, Object>> findScratchoffByLsatCreateTime(Map<String, String> params) throws CustomException {
        List<Map<String, Object>> result;

        //初次获取
        if (com.lt.test.common.util.StringUtils.isNullOrTrimEmpty(params.get("lastOrderTime"))) {
            try {
                result = shopMapper.findTenScratchoff(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取初始化十条刮刮奖中奖失败");
            }
        } else {
            try {
                result = shopMapper.findScratchoffByLastOrderTime(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("根据最后更新时间获取刮刮奖中奖失败");
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> findScratchoffDayData(Map<String, String> params) throws CustomException {
        Date firstDay = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2016-04-11";
        try {
            params.put("firstDayStr", firstDayStr);
            List<Map<String, Object>> SPLOrderDayList = shopMapper.findScratchoffDayData(params);
            Map<String, Object> result = new HashMap<>(3, 1.0F);
            List names = new ArrayList(10);


            for (Map<String, Object> SPLOrderDay : SPLOrderDayList) {
                String name = SPLOrderDay.get("name").toString();
                String value = SPLOrderDay.get("value").toString();
                String nameAndValue = name + "：" + value;
                names.add(nameAndValue);
                SPLOrderDay.put("name", nameAndValue);
            }

            result.put("names", names);
            result.put("data", SPLOrderDayList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按天查询刮刮奖中奖统计失败");
        }
    }

    @Override
    public Map<String, Object> findScratchoffMonthData(Map<String, String> params) throws CustomException {
        Date firstDay = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2016-04-11";
        try {
            params.put("firstDayStr", firstDayStr);
            List<Map<String, Object>> SPLOrderDayList = shopMapper.findScratchoffMonthData(params);
            Map<String, Object> result = new HashMap<>(3, 1.0F);
            List names = new ArrayList(10);


            for (Map<String, Object> SPLOrderDay : SPLOrderDayList) {
                String name = SPLOrderDay.get("name").toString();
                String value = SPLOrderDay.get("value").toString();
                String nameAndValue = name + "：" + value;
                names.add(nameAndValue);
                SPLOrderDay.put("name", nameAndValue);
            }
            result.put("names", names);
            result.put("data", SPLOrderDayList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按月查询刮刮奖中奖统计失败");
        }
    }

    @Override
    public Map<String, Object> findScratchoffWeekData(Map<String, String> params) throws CustomException {
        Date firstDay = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-ww");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2016-04-11";
        try {
            params.put("firstDayStr", firstDayStr);
            List<Map<String, Object>> SPLOrderDayList = shopMapper.findScratchoffWeekData(params);
            Map<String, Object> result = new HashMap<>(3, 1.0F);
            List<String> names = new ArrayList<>(10);


            for (Map<String, Object> SPLOrderDay : SPLOrderDayList) {
                String name = SPLOrderDay.get("name").toString();
                String value = SPLOrderDay.get("value").toString();
                String nameAndValue = name + "：" + value;
                names.add(nameAndValue);
                SPLOrderDay.put("name", nameAndValue);
            }
            result.put("names", names);
            result.put("data", SPLOrderDayList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按月查询刮刮奖中奖统计失败");
        }
    }

    @Override
    public Map<String, Object> findResidueScratchoff(Map<String, String> params) throws Exception {
        List<Map<String, Object>> residueList = shopMapper.findResidueScratchoff(params);
        Map<String, Object> result = new HashMap<>(3, 1.0F);
        List<String> names = new ArrayList<>(10);


        for (Map<String, Object> residue : residueList) {
            String name = residue.get("name").toString();
            String value = residue.get("value").toString();
            String nameAndValue = name + "：" + value;
            names.add(nameAndValue);
            residue.put("name", nameAndValue);
        }
        result.put("names", names);
        result.put("data", residueList);
        return result;
    }

    @Override
    public List<Map<String, Object>> getScratchoffByTime(Map<String, String> stringMap) throws CustomException {
        stringMap = getBeginTime(stringMap);
        CustomUser customUser = null;
        try {
            customUser = userMapper.findCustomUserById(stringMap.get("userId"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询用户详细信息失败");
        }
        if (com.lt.test.common.util.StringUtils.isNot_NullOrTrimEmpty(customUser.getMaterialCompany())) {
            stringMap.put("source", customUser.getMaterialCompany());
        }
        try {
            List<Map<String, Object>> result = shopMapper.getScratchoffByBeginTimeAndEndTime(stringMap);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("根据时间查询中奖记录失败");
        }

    }

    @Override
    public List<Map<String, Object>> getShipmentOrderByTime(Map<String, String> stringMap) throws CustomException {
        stringMap = getBeginTime(stringMap);

        Integer pageSize = Integer.valueOf(stringMap.get("pageSize"));

        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));

        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());

        try {
            return shopMapper.getShipmentOrderByBeginTimeAndEndTime(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("根据时间查询扫码出库记录失败");
        }
    }

    @Override
    public PageDTO<Map<String, Object>> selectStock(Map<String, String> stringMap) throws CustomException {
        Integer pageSize = 10;
        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));
        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());

        try {
            List<Map<String, Object>> dataList = shopMapper.selectStockByShopNameAndShopType(stringMap);
            int recordCount = shopMapper.selectStockCountByShopNameAndShopType(stringMap);
            PageDTO<Map<String,Object>> result = new PageDTO<>(page.intValue(), pageSize, dataList, recordCount);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取库存数据失败");
        }
    }

    @Override
    public PageDTO<Map<String, Object>> selectStocks(Map<String, String> stringMap) throws CustomException {
        Integer pageSize = 10000;
        try {
            List<Map<String, Object>> dataList = shopMapper.selectStockByShopNameAndShopTypes(stringMap);
            int recordCount = shopMapper.selectStockCountByShopNameAndShopType(null);
            PageDTO<Map<String,Object>> result = new PageDTO<>(1, pageSize, dataList, recordCount);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取库存数据失败");
        }
    }

    //导出卷烟订购表
    @Override
    public PageDTO<Map<String, Object>> exportKtTobaccoOrder(Map<String, String> stringMap) throws CustomException {
        Integer pageSize = 10000;
        String shopType = stringMap.get("shopType") == null ? "" : stringMap.get("shopType").toString();
        if (!shopType.equals("")){
            String type = "";
            String[] shopTypeId = shopType.split(",");
            for (int i = 0; i < shopTypeId.length; i++){
                String str = shopTypeId[i];
                System.out.println(shopTypeId.length);
                if(shopTypeId.length == 1){
                    type = "'" + str + "'";
                    break;
                }
                if(i < shopTypeId.length - 1) {
                    if(type.equals("")) {
                        type = "'" + str;
                    }else {
                        type = type + "','" + str;
                    }
                }else {
                    type = type + "','" + str + "'";
                }
            }
            stringMap.put("shopType", type);
        }


        try {
            List<Map<String, Object>> dataList = shopMapper.exportKtTobaccoOrder(stringMap);
            System.out.println("dataList ii" + dataList);
            int recordCount = shopMapper.selectStockCountByShopNameAndShopType(null);
            PageDTO<Map<String,Object>> result = new PageDTO<>(1, pageSize, dataList, recordCount);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取库存数据失败");
        }
    }
    
    @Override
    public List<Map<String,Object>>  selectStockToExcel(Map<String, String> stringMap) throws Exception {

        Integer pageSize = Integer.valueOf(stringMap.get("pageSize"));

        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));

        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());

        try {
            List<Map<String, Object>> dataList = shopMapper.selectStockByShopNameAndShopType(stringMap);
            return dataList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取库存数据失败");
        }



    }

    @Override
    public List<Map<String, Object>> getShopNameToSelect(Map<String, String> params) throws CustomException {


        String quXianName = params.get("quXianName");
        if (quXianName != null && !quXianName.equals("")) {
            String channelId = null;
            try {
                channelId = splOrderMapper.getIdByChannleName(quXianName);

            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取区县失败");
            }
            params.put("parentChannelId", channelId);
        }
        try {
            return shopMapper.getShopNameToSelect(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取店铺名称失败");
        }
    }

    @Override
    public Map<String, Object> getStockStatistics(Map<String, String> params) throws CustomException {
        Map<String, Object> resutl = new HashMap<>(3, 1.0F);
        List<Map<String, Object>> pricesAndStockStatistics = new ArrayList<>(1);
        try {
            pricesAndStockStatistics = shopMapper.getPricesAndStockStatistics(params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<String> stockNames = new ArrayList<>();
        List<String> priceNames = new ArrayList<>();
        List<Map<String, Object>> stockValues = new ArrayList<>();
        List<Map<String, Object>> priceValues = new ArrayList<>();


        for (Map<String, Object> pricesAndStockStatistic : pricesAndStockStatistics) {
            String prodTypeName = pricesAndStockStatistic.get("prodTypeName").toString();
            String stocks = pricesAndStockStatistic.get("stocks").toString();
            String prices = pricesAndStockStatistic.get("prices").toString();

            String stockName = prodTypeName + "：" + stocks;
            String priceName = prodTypeName + "：" + prices;

            stockNames.add(stockName);
            priceNames.add(priceName);

            Map<String, Object> stockValue = new HashMap<>(2, 1.0F);
            stockValue.put("name", stockName);
            stockValue.put("value", Long.valueOf(stocks));
            stockValues.add(stockValue);

            Map<String, Object> priceValue = new HashMap<>(2, 1.0F);
            priceValue.put("name", priceName);
            priceValue.put("value", Double.valueOf(prices));
            priceValues.add(priceValue);
        }

        resutl.put("stockNames", stockNames);
        resutl.put("priceNames", priceNames);
        resutl.put("stockValues", stockValues);
        resutl.put("priceValues", priceValues);
        return resutl;
    }

    private Map<String, String> getBeginTime(Map<String, String> stringMap) {
        if (stringMap.get("beginTime") == null || stringMap.get("beginTime").equals("")) {
            Calendar ca = Calendar.getInstance();
            ca.setTime(new Date());
            ca.add(Calendar.MONTH, -1);
            Date firstDay = ca.getTime();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd ");
            stringMap.put("beginTime", sf.format(firstDay));
        }
        return stringMap;
    }

    private List<Map<String, Object>> putProductName(List<Map<String, Object>> result) {
        Map<String, String> params = new HashMap<>(2, 1.0F);
        for (Map<String, Object> map : result) {
            String timeStr = map.get("timeStr").toString();
            String shopId = map.get("shopId").toString();
            params.put("shopId", shopId);
            params.put("timeStr", timeStr);
            logger.info("getProductNameByTimeStr params is : " + params);
            String productName = null;
            try {
                productName = shopMapper.getProductNameByTimeStr(params);
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("productName", productName);
            logger.info("productName is : " + productName);
        }
        return result;
    }

    @Override
    public List<Map<String, String>> getProductThreeName() throws CustomException {
        List<Map<String, String>> result = new ArrayList<>(4);
        try {
            result.addAll(shopMapper.getProductFactoryName());
            result.addAll(shopMapper.getProductBandName());
            result.addAll(shopMapper.getProductProductName());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取商品属性树失败");
        }
    }

    @Override
    public SuperMarketUserDTO getShopAndUserByShopIdAndUserId(SuperMarketUserDTO user) throws CustomException {
        try {
            return shopMapper.getShopAndUserByShopIdAndUserId(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取店铺和用户信息失败");
        }
    }

    @Override
    public Map<String, String> getOrderState(String orderId) throws CustomException {
        try {
            return shopMapper.getOrderState(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取订单交易信息失败");
        }
    }


    public Map<String,Map<String, String>> getSynthesisSelect_OLD(Map<String, String> stringMap) throws Exception {
        Map<String,Map<String, String>> result = new HashMap<>(6,1.0F);
        //9个单指标统计
        Map<String, String> numResult = new HashMap<>(9, 1.0F);
        String registerNum = "获取出错",
                bindCarNum = "获取出错",
                expNum = "获取出错",
                dingYanNum = "获取出错",
                payNum = "获取出错",
                payCountNum = "获取出错",
                payAmt = "获取出错",
                orderQty = "获取出错",
                stockNum = "获取出错";

        stringMap.put("currentInventoryDate",getCurrentInventoryDate(stringMap.get("endTime")));

        try {
            registerNum = shopMapper.getSynthesis_registerNum(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            bindCarNum = shopMapper.getSynthesis_bindCarNum(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            expNum = shopMapper.getSynthesis_expNum(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            dingYanNum = shopMapper.getSynthesis_dingYanNum(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            payNum = shopMapper.getSynthesis_payNum(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            payCountNum = shopMapper.getSynthesis_payCountNum(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            payAmt = shopMapper.getSynthesis_payAmt(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            orderQty = shopMapper.getSynthesis_orderQty(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            stockNum = shopMapper.getSynthesis_stockNum(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        numResult.put("registerNum", registerNum);
        numResult.put("bindCarNum", bindCarNum);
        numResult.put("expNum", expNum);
        numResult.put("dingYanNum", dingYanNum);
        numResult.put("payNum", payNum);
        numResult.put("payCountNum", payCountNum);
        numResult.put("payAmt", payAmt);
        numResult.put("orderQty", orderQty);
        numResult.put("stockNum", stockNum);


        result.put("numResult",numResult);
        return result;
    }

    @Override
    public Map<String,Map<String, String>> getSynthesisSelect(Map<String, String> stringMap) throws Exception {
        Map<String,Map<String, String>> result = new HashMap<>(2,1.0F);
        //9个单指标统计
        stringMap.put("currentInventoryDate",getCurrentInventoryDate(stringMap.get("endTime")));
        Map<String, String> numResult = shopMapper.getHomePageProcess(stringMap);

        result.put("numResult",numResult);
        return result;
    }

    @Override
    public Map<String, Map<String, String>> getBigScreenStatisticsData(Map<String, String> stringMap) {
        Map<String,Map<String, String>> result = new HashMap<>(4,1.0F);
        //
        stringMap.put("currentInventoryDate",getCurrentInventoryDate(stringMap.get("endTime")));
        stringMap.put("quXianName","水城县烟草专卖局（分公司）");
        Map<String, String> scd = shopMapper.getHomePageProcess(stringMap);

        stringMap.put("quXianName","钟山区烟草专卖局（分公司）");
        Map<String, String> zsd = shopMapper.getHomePageProcess(stringMap);

        stringMap.put("quXianName","六枝特区烟草专卖局（分公司）");
        Map<String, String> lzd = shopMapper.getHomePageProcess(stringMap);

        stringMap.put("quXianName","盘县烟草专卖局（分公司）");
        Map<String, String> psd = shopMapper.getHomePageProcess(stringMap);

        result.put("scd",scd);
        result.put("zsd",zsd);
        result.put("lzd",lzd);
        result.put("psd",psd);
        return result;
    }

    @Override
    public List<Map<String, Object>> getBigScreenData(Map<String, Object> params) {
        List<Map<String, Object>> bigScreenData = shopMapper.getBigScreenData(params);
        return bigScreenData;
    }

    @Override
    public PageDTO<Map<String, String>> getStockAnalyzeByPageQuery(Map<String, String> stringMap) throws Exception {
        Integer pageSize = 10;
        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));
        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
        stringMap.put("currentInventoryDate",getCurrentInventoryDate(stringMap.get("endOperatorTime")));

        List<Map<String,String>> dataList = null;
        int recordCount = 0;
        try {
            if ("cust".equals(stringMap.get("type"))) {
                dataList = shopMapper.getCustAnalyzeByPageQuery(stringMap);
                recordCount = shopMapper.getCustAnalyzeCountByPageQuery(stringMap);
            }else {
                dataList = shopMapper.getProductAnalyzeByPageQuery(stringMap);
                recordCount = shopMapper.getProductAnalyzeCountByPageQuery(stringMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("分页获取库存统计数据失败");
        }
        PageDTO<Map<String,String>> result = new PageDTO<>(page.intValue(), pageSize, dataList, recordCount);
        return result;
    }

    @Override
    public List<Map<String, Object>> getStockAnalyzeExportExcelData(Map<String, String> stringMap) throws Exception {
        List<Map<String,Object>> dataList = null;
        stringMap.put("currentInventoryDate",getCurrentInventoryDate(stringMap.get("endOperatorTime")));
        if ("cust".equals(stringMap.get("tableType"))) {
            dataList = shopMapper.getStockAnalyzeCustExportExcelData(stringMap);
        }else {
            dataList = shopMapper.getStockAnalyzeProductExportExcelData(stringMap);
        }

        return dataList;
    }


    private String getCurrentInventoryDate(String queryEndDate) {
        if (queryEndDate !=null && !queryEndDate.trim().equals("")) {
            return queryEndDate;
        }
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
       // int day = calendar.get(Calendar.DATE);
        calendar.add(Calendar.DATE, -1);
        return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
    }

    @Override
    public List<Map<String, Object>> selectCustNameToSelected(Map<String, String> params) throws Exception {
        return shopMapper.selectCustNameToSelected(params);
    }


    @Override
    public List<Map<String, Object>> getDaZhuanPanPrizeByPageQuery(Map<String, String> stringMap) throws CustomException {

        Integer pageSize = Integer.valueOf(stringMap.get("pageSize"));
        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));

        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());

        try {
            return shopMapper.getDaZhuanPanPrizeByPageQuery(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询失败");
        }
    }

    @Override
    public Map<String,Object> getCustomerInfoByIdAndType(String customerId,String shopId, String type) {
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        params.put("shopId", shopId);
        if ("3".equals(type)) {
            return shopMapper.getCustomerByFaceId(params);
        }else {
            return shopMapper.getCustomerBySysUserId(customerId);
        }
    }
}
